<template>
<div>
        <el-form>
            <el-form-item>
            <el-date-picker type="date" placeholder="请选择开始时间" value-format="yyyy-MM-dd" v-model="reportStartTime" v-if="hackReset">
            </el-date-picker>
            <el-date-picker type="date" placeholder="请选择结束时间" value-format="yyyy-MM-dd" v-model="reportEndTime" v-if="hackReset">
            </el-date-picker>
            <el-button @click="fillData()">查询</el-button>
            </el-form-item>
            <el-form-item>
                <div class="row">
                    <!-- Pie -->
                    <div class="col-md-6 col-sm-12">
                        <div class="box box-success">
                            <div class="box-header with-border">
                                <h3 class="box-title" id="titlePieDay"></h3>
                                <div class="box-tools pull-right">
                                    <button type="button" class="btn btn-box-tool" @click="DownloadImage('pieDay','title')"><i class="fa fa-download"></i></button>
                                    <button type="button" class="btn btn-box-tool" @click="Print('pieDay','title')"><i class="fa fa-print"></i></button>
                                    <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
                                </div>
                            </div>
                            <div class="box-body chart-responsive">
                                <div class="chart" style="position: relative; overflow: visible; height: 300px;" id="chartPieDay">
                                    <canvas id="pieDay" style="height: 300px;"></canvas>
                                </div>

                            </div>
                        </div>
                    </div>
                    <!-- Bar -->
                    <div class="col-md-6 col-sm-12">
                        <div class="box box-success">
                            <div class="box-header with-border">
                                <h3 class="box-title" id="titleBarDay"></h3>
                                <div class="box-tools pull-right">
                                    <button type="button" class="btn btn-box-tool" @click="DownloadImage('barDay','title')"><i class="fa fa-download"></i></button>
                                    <button type="button" class="btn btn-box-tool" @click="Print('barDay','title')"><i class="fa fa-print"></i></button>
                                    <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
                                </div>
                            </div>
                            <div class="box-body chart-responsive">
                                <div class="chart" style="position: relative; overflow: visible; height: 300px;" id="chartBarDay">
                                    <canvas id="barDay" style="height: 300px;"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-form-item>
        </el-form>
</div>
</template>
<script>
/* eslint-disable */
import $ from 'jquery'
import Chart from 'chart.js'
import { canvasSaveFile, canvasPrint } from '@/utils/image.min.js'
export default {
        components: {
        },
    data () {
        return {
      reportStartTime: '2018-09-01', // 申报开始时间
      reportEndTime: '2018-09-10', // 申报结束时间
      hackReset: true
        }
    },
    mounted () {
        this.fillData()
        // drawChart(){}
    },
    methods: {
        fillData () {
            this.$http.get(
            `${window.SITE_CONFIG['baseURL']}/demo/charts2/list`,
            {
                mode: 'no-cors',
                headers: {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'application/json'
                },
                withCredentials: true,
                params: {
                'spName': 'SP_EMS_Total_Detail',
                'spParams': 'Day,0,' + this.reportStartTime + ',' + this.reportEndTime + ',000'
                // LoadData('Day', sTime, eTime, "000")
                }
            }
            ).then(({data}) => {
                DataHandler(data,this.reportStartTime,this.reportEndTime)
            })
        },
        DownloadImage (str1, str2) {
            DownloadImage(str1, str2)
        },
        Print (str1, str2) {
            Print(str1, str2)
        }
    }
}

var dataItem = ['ASSEMBLY', 'ASSEMBLY_Lighting', 'ASSEMBLY_airConditioning', 'ASSEMBLY_Equipment']
var desc = function (x, y) {
        return (x.value < y.value) ? 1 : -1
    }
var chartPieDay = ''
var chartBarDay = ''
function DataHandler (data,datestart,datesend) {
       // data[0].timeType, data[0].dataItem, data[0].result
       if (data == null || data === '') {
            return
        }
        var timeType = 'Day'
        var configPie
        var configBar
        var columns
        var dataSet
        var result
        result = AutoHandler(data.results)
        configPie = result.configPie
        configBar = result.configBar
        columns = result.columns
        dataSet = result.dataSet
        configPie.options.legend.labels.generateLabels = PieLegendGenerateLabels()
        // configPie.options.tooltips.callbacks.label = PieTooltipsCallbacksLabel('chartPieDay')
        $('#pieDay').remove() // this is my <canvas> element
        $('#chartPieDay').append('<canvas id="pieDay" style="height: 300px;"></canvas>')
        $('#titlePieDay').text(datestart + ' ~ ' +datesend)
        
        var pie  = document.getElementById('pieDay')
        new Chart(pie, configPie)
        // configBar.options.tooltips.custom = BarCustomTooltips('chartBarDay')
        $('#barDay').remove() // this is my <canvas> element
        $('#chartBarDay').append('<canvas id="barDay" style="height: 300px;"></canvas>')
        $('#titleBarDay').text(datestart + ' ~ ' +datesend)
        var canvasBar  = document.getElementById('barDay')
        new Chart(canvasBar, configBar)
        }    
function AutoHandler (data) {
        var configPie = CreateConfigPieOptions()
        var configBar = CreateConfigBarOptions()
        var columns = []
        var dataSet = []
        var DateArr = []
        var TotalArr = []
        var ASSEMBLYArr = []
        var ASSEMBLY_LightingArr = []
        var ASSEMBLY_airConditioningArr = []
        var ASSEMBLY_EquipmentArr = []
        var sumASSEMBLY = 0
        var sumASSEMBLY_Lighting = 0
        var sumASSEMBLY_airConditioning = 0
        var sumASSEMBLY_Equipment = 0
        var str2 = "{ title: 'Date'}"
        var colorArr = []
        colorArr.push('0,192,239')
        colorArr.push('221,75,57')
        colorArr.push('0,166,90')
        colorArr.push('243,156,18')
        colorArr.push('102,102,204')
        colorArr.push('255,153,102')
        colorArr.push('51,153,153')
        colorArr.push('204,153,51')
        var resultsql = ''
        // 抓取横坐标轴数据
        for (var i0 = 0; i0 < data.length; i0++)
        {
             if (data[i0].label === 'cDate') {
                DateArr = data[i0].label_data
                dataSet.push(DateArr)
            } 
        }
        configBar.data.labels = DateArr
        for (var i = 0; i < dataItem.length; i++) {
            var datasets
            var str = ''
            // 对纵坐标数据赋值
            for (var i2 = 0; i2 < data.length; i2++) {
                var sumAll = 0
                var tempArray = [] 
                if(data[i2].label === dataItem[i]) {
                    eval(dataItem[i] + 'Arr = ArrFloatToFixed((data[i2].label_data), 1);')
                    // sumAll += FloatToSum((data[i2].label_data),1);
                    eval('sum' + dataItem[i] + ' =  FloatToSum((data[i2].label_data),1);')
                    // eval('tempArray.push(FloatToFixed((data[i2].label_data),1));')
                    // TotalArr.push(sumAll)
                    dataSet.push(ArrFloatToFixed((data[i2].label_data),1))
                    str = 'datasets = {'
                    str += "type: 'bar',"
                    str += "label: '" + dataItem[i] + "',"
                    str += "backgroundColor: 'rgba(" + colorArr[i % 8] + ",0.5)',"
                    str += "borderColor: 'rgba(" + colorArr[i % 8] + ",0.5)',"
                    str += 'fill: false,'
                    str += 'borderWidth: 1,'
                    str += 'radius: 2,'
                    str += 'data: ' + dataItem[i] + 'Arr}'
                    eval(str)
                    configBar.data.datasets.push(datasets)
                    str2 += ",{ title: '" + dataItem[i] + "'}"
                }
            }
            if (i !== 0) {
                resultsql += ','
            }
            resultsql += "{ name: '" + dataItem[i] + "'" + ', value: sum' + dataItem[i] + ", color: 'rgba(" + colorArr[i % 8] + ",0.6)' }"
        }
        // 获取TotalArr信息TotalArr
        for (var k = 1; k < dataSet.length; k++)
        {
          // k=0 是日期所以不需要，从K=1开始计算
          for (var kk = 0; kk < dataSet[k].length; kk++)
          {
              if (k === 1)
              {
              TotalArr.push(dataSet[k][kk])
              }
              else
              {
                  TotalArr[kk]+=dataSet[k][kk]
              }
          }
        }
        columns = eval('[' + str2 + ']')
        var result = eval('[' + resultsql + ']')
        // eval(result)
        // result.sort(desc)
        for (var i3 = 0; i3 < result.length; i3++) {
            configPie.data.labels.push(result[i3].name)
            configPie.data.datasets[0].data.push(result[i3].value)
            configPie.data.datasets[0].backgroundColor.push(result[i3].color)
        }
        var totalDatasets = {
            type: 'line',
            label: 'Total',
            backgroundColor: 'rgba(255, 255, 255, 0)',
            borderColor: 'rgba(0, 255, 0, 1)',
            fill: false,
            borderWidth: 2,
            radius: 2,
            data: TotalArr
        }
        configBar.data.datasets.push(totalDatasets)
        return {
            configPie: configPie,
            configBar: configBar,
            columns: columns,
            dataSet: dataSet
        }
    }
function ArrFloatToFixed (value, precision) {
    var returmArr = []
    if (precision == null || precision === '') {
            precision = 1
        }
    for (var i = 0; i < value.length; i++) {
        returmArr[i] = parseFloat(parseFloat(value[i]).toFixed(precision))
    }
    return returmArr
    }

function FloatToFixed(value, precision) {
        if (precision == null || precision == "") {
            precision = 1;
        }
        return parseFloat(parseFloat(value).toFixed(precision));
    }
function FloatToSum (value, precision) {
    var returmArr = 0
    if (precision == null || precision === '') {
            precision = 1
        }
    for (var i = 0; i < value.length; i++) {
        returmArr += parseFloat(parseFloat(value[i]).toFixed(precision))
    }
    return returmArr
    }
function CreateConfigPieOptions () {
        return {
            type: 'pie',
            data: {
                labels: [],
                datasets: [{
                    data: [],
                    backgroundColor: [],
                    pointStyle: 'rectRot'
                }]
            },
            options: {
                responsive: true,
                title: {
                    display: false,
                    padding: 0,
                    text: 'pie year',
                    fontColor: '#666',
                    fontFamily: "'微软雅黑', sans-serif",
                    fontSize: 15
                },
                legend: {
                    display: true,
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        fontFamily: '微软雅黑',
                        padding: 5,
                        generateLabels: ''
                    }
                },
                tooltips: {
                    // callbacks: {
                    //     label: ''
                    // }
                }
            },
            plugins: {
                beforeUpdate: function (chart) {
                    chart.height = 300
                }
            }
        }
    }
function CreateConfigBarOptions () {
        return {
            type: 'bar',
            data: {
                labels: [],
                datasets: []
            },
            options: {
                animation: {
                    duration: '2000',
                    easing: 'easeOutBack'
                },
                responsive: true,
                maintainAspectRatio: false,
                title: {
                    display: false,
                    padding: 0,
                    text: 'bar year',
                    fontColor: '#666',
                    fontFamily: "'微软雅黑', sans-serif",
                    fontSize: 15
                },
                scales: {
                    xAxes: [{
                        stacked: true,
                        display: true,
                        gridLines: {
                            display: false,
                            drawTicks: true
                        }
                    }],
                    yAxes: [{
                        stacked: true,
                        display: true,
                        gridLines: {
                            drawTicks: false
                        }
                    }]
                },
                legend: {
                    display: true,
                    position: 'top'
                },
                tooltips: {
                    // enabled: false,
                    // mode: 'x-axis',
                    // position: 'nearest'
                    // custom: function (tooltip)
                }
            },
            plugins: {
                beforeUpdate: function (chart) {
                    chart.height = 300
                }
            }
        }
    }
function PieLegendGenerateLabels() {
        var fun
        eval("fun = function (chart) {var total = 0;for (var i = 0; i < chart.data.datasets[0].data.length; i++) {total += parseFloat(chart.data.datasets[0].data[i]);}total = FloatToFixed(total, 1);var data = chart.data;var helpers = Chart.helpers;if (data.labels.length && data.datasets.length && total > 0) { return data.labels.map(function (label, i) {var meta = chart.getDatasetMeta(0);var ds = data.datasets[0];var arc = meta.data[i]; var custom = arc && arc.custom || {};var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault;var arcOpts = chart.options.elements.arc;var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);var text = label + ': ' + (parseFloat(data.datasets[0].data[i] / total * 100).toFixed(1)) + '%[' + data.datasets[0].data[i] + 'unitKWH' + ']';return {text: text,fillStyle: fill,strokeStyle: stroke,lineWidth: bw,hidden: isNaN(ds.data[i]) || meta.data[i].hidden,index: i};});}return [];}")
        return fun
    }
function PieTooltipsCallbacksLabel(chart) {
        if (chart == null || chart === '') {
            return
        } else {
            var fun
            eval("fun = function (tooltipItem, data) {var total = 0;for (var i = 0; i < " + chart + ".data.datasets[0].data.length; i++) {total += parseFloat(" + chart + ".data.datasets[0].data[i]);}total = FloatToFixed(total, 1);var index = tooltipItem.index;var value = data.datasets[0].data[index];var label = data.labels[index] + ': ' + (parseFloat(value / total * 100).toFixed(1)) + '%[' + value + 'unitKWH' + ']';return label;}");
            return fun
        }
    }
function BarCustomTooltips(chart) {
        if (chart == null || chart == "") {
            return;
        } else {
            var fun;
            eval("fun = function (tooltip) {var dataChart = " + chart + ".data; var tooltipEl = document.getElementById('chartjs-tooltip'); if (tooltip.opacity == 0) { tooltipEl.style.opacity = 0; $('#chartjs-tooltip').remove(); return } var index; if (tooltip.dataPoints) { index = tooltip.dataPoints[0].index } else { return } if (!tooltipEl) { tooltipEl = document.createElement('div'); tooltipEl.id = 'chartjs-tooltip'; tooltipEl.innerHTML = '<label></label><table  border=\"1\" cellspacing=\"0\" cellpadding=\"0\"></table>'; this._chart.canvas.parentNode.appendChild(tooltipEl) } tooltipEl.classList.remove('above', 'below', 'no-transform'); if (tooltip.yAlign) { tooltipEl.classList.add(tooltip.yAlign) } else { tooltipEl.classList.add('no-transform') } function getBody(bodyItem) { return bodyItem.lines } if (tooltip.body) { var titleLines = tooltip.title || []; var bodyLines = tooltip.body.map(getBody); var innerHtml = '<thead>'; if (index == 0) { innerHtml += '<tr>'; innerHtml += '<th>jsName</th>'; innerHtml += '<th> ' + dataChart.labels[index] + ' </th>'; innerHtml += '</tr>' } else { innerHtml += '<tr>'; innerHtml += '<th>jsName</th>'; innerHtml += '<th> ' + dataChart.labels[index - 1] + ' </th>'; innerHtml += '<th> ' + dataChart.labels[index] + ' </th>'; innerHtml += '<th>jsGrowth</th>'; innerHtml += '</tr>' } innerHtml += '</thead><tbody>'; if (index == 0) { for (var i = 0; i < tooltip.dataPoints.length; i++) { var datasetIndex = tooltip.dataPoints[i].datasetIndex; var label = dataChart.datasets[datasetIndex].label; var style = 'background:' + dataChart.datasets[datasetIndex].backgroundColor + '; '; style += 'border:2px solid ' + dataChart.datasets[datasetIndex].borderColor + '; '; style += 'border-width: 2px;'; var span = '<span class=\"chartjs-tooltip-key\" style=\"' + style + '\"></span>'; innerHtml += '<tr>'; innerHtml += '<td> ' + span + label + ' </td>'; innerHtml += '<td> ' + dataChart.datasets[datasetIndex].data[index] + ' ' + 'unitKWH' + ' </td>'; innerHtml += '</tr>' } } else { for (var i = 0; i < tooltip.dataPoints.length; i++) { var datasetIndex = tooltip.dataPoints[i].datasetIndex; var label = dataChart.datasets[datasetIndex].label; var style = 'background:' + dataChart.datasets[datasetIndex].backgroundColor + '; '; style += 'border:2px solid ' + dataChart.datasets[datasetIndex].borderColor + '; '; style += 'border-width: 2px;'; var span = '<span class=\"chartjs-tooltip-key\" style=\"' + style + '\"></span>'; innerHtml += '<tr>'; innerHtml += '<td> ' + span + label + ' </td>'; var lastMonth = dataChart.datasets[datasetIndex].data[index - 1]; var thisMonth = dataChart.datasets[datasetIndex].data[index]; var growth = \"\"; if (lastMonth == 0) { growth = \"0%\" } else { var percent = 0; if (thisMonth != lastMonth) { percent = (parseInt((thisMonth - lastMonth) / lastMonth * 100)) } if (percent > 0) { growth = '+' } growth += percent + \"%\" } innerHtml += '<td> ' + lastMonth + ' ' + 'unitKWH' + ' </td>'; innerHtml += '<td> ' + thisMonth + ' ' + 'unitKWH' + ' </td>'; innerHtml += '<td> ' + growth + ' </td>'; innerHtml += '</tr>' } } innerHtml += '</tbody>'; var tableRoot = tooltipEl.querySelector('table'); tableRoot.innerHTML = innerHtml; tooltipEl.querySelector('label').innerHTML = tooltip.title[0] } var positionY = this._chart.canvas.offsetTop - 150; tooltipEl.style.opacity = 1; var minLeft = tooltipEl.offsetWidth / 2; var maxLeft = this._chart.width - tooltipEl.offsetWidth + minLeft; if (tooltip.caretX < minLeft) { tooltipEl.style.left = minLeft } else if (tooltip.caretX > maxLeft) { tooltipEl.style.left = maxLeft } else { tooltipEl.style.left = tooltip.caretX } tooltipEl.style.top = positionY + tooltip.caretY + 'px'; tooltipEl.style.fontFamily = tooltip._bodyFontFamily; tooltipEl.style.fontSize = tooltip.fontSize; tooltipEl.style.fontStyle = tooltip._fontStyle; tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';};");
            return fun;
        }
    }
function DownloadImage (Id, title) {
        var canvas = document.getElementById(Id)
        // eval('title = langAnalysis.' + title);
        canvasSaveFile(canvas, 'png', title)
    }
function Print (Id, title) {
    var canvas = document.getElementById(Id)
    // eval('title = langAnalysis.' + title);
     canvasPrint(canvas, title)
}
</script>
